package tum0r.webengine.models.utils.vercode

import tum0r.webengine.config.ApplicationConfig
import java.awt.Graphics2D
import java.awt.font.FontRenderContext
import java.awt.geom.AffineTransform
import java.awt.image.BufferedImage

/**
 * 说明: 正常的验证码
 *
 * 创建者: tum0r
 *
 * 时间: 2021/8/29 18:24
 */
class NormalVerificationCode(length: Int = 6, pointDivide: Int = 15, lineCount: Int = 5) : VerificationCodeBase(length, pointDivide, lineCount) {
    /**
     * 排除验证码字符
     */
    val except = ArrayList<Char>()

    init {
        except.add('0')
        except.add('o')
        except.add('O')
    }

    override fun generateCode(): String {
        val result = StringBuilder()
        if (length > 0) {
            while (result.length != length) {
                val c = when (random.nextInt(3)) {
                    0 -> '0' + random.nextInt(10)
                    1 -> 'a' + random.nextInt(26)
                    else -> 'A' + random.nextInt(26)
                }
                if (!except.contains(c)) result.append(c)
            }
        }
        return result.toString()
    }

    override fun newCode(code: String, answer: String) {
        this.answer = answer
        val bounds = ApplicationConfig.FONT.getStringBounds(code, FontRenderContext(AffineTransform(), true, true))
        val width = 10 + bounds.width.toInt()
        val height = 30 + bounds.height.toInt()
        this.codeImage = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
        fillImage()
        val graphics = this.codeImage.graphics as Graphics2D
        graphics.font = ApplicationConfig.FONT
        val widthAvg = bounds.width.toInt() / code.length
        for (i in code.indices) {
            graphics.color = randomColor(0)
            graphics.drawString(code.substring(i, i + 1), 5 + i * widthAvg, 15 + bounds.height.toInt() * 5 / 6)
        }
        disturbPoint()
        disturbLine()
    }

    override fun newCode() = newCode("")
}